#!/usr/bin/env python3
"""
图标转换工具
将 PNG/JPG 图片转换为 ICO 格式，用于应用程序图标

使用方法：
python convert_icon.py input_image.png

需要安装 Pillow：
pip install Pillow
"""

import sys
from pathlib import Path

try:
    from PIL import Image
except ImportError:
    print("❌ 需要安装 Pillow 库: pip install Pillow")
    sys.exit(1)

def convert_to_ico(input_path, output_path=None):
    """将图片转换为 ICO 格式"""
    input_path = Path(input_path)
    
    if not input_path.exists():
        print(f"❌ 文件不存在: {input_path}")
        return False
    
    if output_path is None:
        output_path = input_path.with_suffix('.ico')
    else:
        output_path = Path(output_path)
    
    try:
        # 打开原图
        with Image.open(input_path) as img:
            # 转换为 RGBA 模式（支持透明度）
            if img.mode != 'RGBA':
                img = img.convert('RGBA')
            
            # 创建多个尺寸的图标
            sizes = [(16, 16), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)]
            icon_images = []
            
            for size in sizes:
                # 调整图片大小，保持宽高比
                resized = img.resize(size, Image.Resampling.LANCZOS)
                icon_images.append(resized)
            
            # 保存为 ICO 格式
            icon_images[0].save(
                output_path, 
                format='ICO', 
                sizes=[(img.width, img.height) for img in icon_images],
                append_images=icon_images[1:]
            )
            
            print(f"✅ 成功转换图标: {input_path} -> {output_path}")
            print(f"📏 包含尺寸: {', '.join([f'{s[0]}x{s[1]}' for s in sizes])}")
            return True
            
    except Exception as e:
        print(f"❌ 转换失败: {e}")
        return False

def main():
    if len(sys.argv) < 2:
        print("📖 使用方法:")
        print("  python convert_icon.py input_image.png [output_icon.ico]")
        print()
        print("📝 支持的输入格式: PNG, JPG, JPEG, BMP, GIF")
        print("📝 输出格式: ICO（包含多个尺寸）")
        return
    
    input_file = sys.argv[1]
    output_file = sys.argv[2] if len(sys.argv) > 2 else None
    
    print(f"🔄 开始转换图标: {input_file}")
    
    if convert_to_ico(input_file, output_file):
        print("🎉 转换完成！")
    else:
        print("💥 转换失败！")

if __name__ == "__main__":
    main()

